#!/bin/bash

# 网关服务控制脚本
# 包含启动、停止、重启功能

APP_NAME="suna-gateway"
PID_FILE="/tmp/${APP_NAME}.pid"
LOG_FILE="/tmp/${APP_NAME}.log"

# 启动服务
start() {
    if [ -f $PID_FILE ]; then
        PID=$(cat $PID_FILE)
        if ps -p $PID > /dev/null; then
            echo "$APP_NAME is already running (PID: $PID)"
            return 1
        else
            # PID文件存在但进程不存在，移除PID文件
            rm $PID_FILE
        fi
    fi
    
    echo "Starting $APP_NAME..."
    nohup python run.py > $LOG_FILE 2>&1 &
    echo $! > $PID_FILE
    echo "$APP_NAME started with PID $(cat $PID_FILE)"
}

# 停止服务
stop() {
    if [ ! -f $PID_FILE ]; then
        echo "$APP_NAME is not running"
        return 1
    fi
    
    PID=$(cat $PID_FILE)
    echo "Stopping $APP_NAME (PID: $PID)..."
    
    # 尝试优雅停止
    kill -TERM $PID
    
    # 等待最多10秒
    COUNT=0
    while [ $COUNT -lt 10 ]; do
        if ! ps -p $PID > /dev/null; then
            break
        fi
        sleep 1
        COUNT=$((COUNT + 1))
    done
    
    # 如果进程仍然存在，强制杀死
    if ps -p $PID > /dev/null; then
        echo "Force killing $APP_NAME..."
        kill -KILL $PID
    fi
    
    rm -f $PID_FILE
    echo "$APP_NAME stopped"
}

# 重启服务
restart() {
    stop
    sleep 2
    start
}

# 查看状态
status() {
    if [ -f $PID_FILE ]; then
        PID=$(cat $PID_FILE)
        if ps -p $PID > /dev/null; then
            echo "$APP_NAME is running (PID: $PID)"
        else
            echo "$APP_NAME is not running but PID file exists"
        fi
    else
        echo "$APP_NAME is not running"
    fi
}

# 查看日志
logs() {
    if [ -f $LOG_FILE ]; then
        tail -f $LOG_FILE
    else
        echo "Log file not found: $LOG_FILE"
    fi
}

# 显示帮助
help() {
    echo "Usage: $0 {start|stop|restart|status|logs}"
    echo "  start   - Start the gateway service"
    echo "  stop    - Stop the gateway service"
    echo "  restart - Restart the gateway service"
    echo "  status  - Check the status of the service"
    echo "  logs    - View the service logs"
}

# 主逻辑
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    status)
        status
        ;;
    logs)
        logs
        ;;
    *)
        help
        exit 1
        ;;
esac

exit 0